 Ext.ns("Pengtu.Ext");
/*
 *CRUD面板基类,继承自EXT的Panel
 */
 Pengtu.Ext.ContractPanel = Ext.extend(Ext.Panel, {
    gridPanel:null,
    gridPanelId: 'gridPanel' + this.ID,
    gridViewConfig: {},
    sm: null,
    store: null,
    baseUrl: null,
    saveUrl: null,
    storeMapping: null,
    pageSize: null,
   	pagingBar: null,
   	dataFields:[],
   	gridPlugins:[],  
    layout :'fit',
    //构造器
    constructor: function(config){
        config = config || {};
        if(!config.width){
         config.width =765;
        }
         if(!config.height){
         config.height =380;
        }
        if(!this.store){
            this.store = new Ext.data.JsonStore({
                id: this.ID,
                url: this.baseUrl + '?method=searchExt',//默认的数据源地址，继承时需要提供
                root: "results",
                totalProperty: "totalCounts",
                remoteSort: true,
                fields: this.storeMapping
            });
        } 
        if(!this.sm){
        this.sm=new Ext.grid.RowSelectionModel({singleSelect:true});
        }
        var viewConfig = Ext.apply({
            forceFit: false
        }, this.gridViewConfig);
        	//添加右键菜单
		var curd = new Ext.menu.Menu({
	    id: 'curd',
	    items:[{text: '保存',handler: this.saveOneData}, {text: '撤销', handler: this.cancelOneData},
	    		'-',
	    	   {text: '查看',handler: this.viewOneData}, {text: '删除', handler: this.deleteOneData},
	    	    '-',
		 	   {text: '新增',handler: this.addOneData}
		 	  ]
			});
        this.gridPanel = new Ext.grid.EditorGridPanel({
            id: Ext.id(),
            store: this.store,         
            cm: this.cm,
            sm: this.sm,
            loadMask: true,
		    border:false,
		    clicksToEdit:2,
		    width:this.width-12,
   			height:380,
   			columnLines:true,
   			enableHdMenu:true,
		    collapsible: true,
            animCollapse: false,
            viewConfig: viewConfig,
            plugins: this.gridPlugins,
       		tbar: [{text: '新增',handler:this.addOneData,scope:this,iconCls:'dt_add'},{text: '保存',handler: this.saveOneData ,scope:this,iconCls:'dt_save'},{text:'删除',handler: this.deleteOneData,scope:this,iconCls:'dt_del'},
        	  '-',
	 		  {text: '保存所有', handler: this.saveMoreData ,scope:this,iconCls:'dt_saveall'},
	 		  '->',{text:'刷新',	handler:this.reloadData ,scope:this,iconCls:'dt_flush'}, '   '],
		    bbar: this.pagingBar
        });        
    //添加右键菜单
		var curdMenu = new Ext.menu.Menu({
		    id: 'curd',
		    items:[{text: '保存',handler: this.saveOneData,scope:this}, {text: '撤销', handler: this.cancelOneData,scope:this},
		    		'-',
		    	  	{text: '查看',handler: this.viewOneData,scope:this}, {text: '删除', handler: this.deleteOneData,scope:this},
		    	    '-',
			 	    {text: '新增',handler: this.addOneData,scope:this}
			 	  ]
				});
		this.gridPanel.on("cellcontextmenu",function(grid,rowIndex, cellIndex, e){
 			var selModel =grid.getSelectionModel();
 			selModel.clearSelections();
 	 		selModel.selectRow(rowIndex);
 			curdMenu.showAt(e.getPoint()); 
		});
        if(this.view){
            Ext.apply(this.gridPanel,{
                view: this.view
            });
        }
       if(this.pageSize){
       	 this.store.load({
            params: {
                start: 0,
                limit: this.pageSize
            }
        });
        } else {
       	 this.store.load();
        }
        var configs = Ext.apply({
            closable: true,
            autoScroll: true,
            items:[this.gridPanel]
        },config);    
        //调用父类的构造器
        Jinyi.project.CrudPanel.superclass.constructor.call(this,configs);
    },
    /**
      *事件
      */
    //查询
    onSearch: function(){
        var keyword = this.keywordText.getValue();//得到输入框的值
        this.store.load({
            params: {
                start: 0,
                limit: 10,
                keyword: keyword
            }
        });
    },
    //刷新
    reloadData: function(){
    	this.store.commitChanges() ;
        this.store.removeAll();
        this.store.reload();
    },
    //初始化窗口（用于新增，修改时）,继承后在createWin中调用该方法显示窗口
    initWin: function(width, height, status){
        var win = new Ext.Window({
            title: "信息（" + status + "）",
            width: width,
            height: height,
            modal: true,
            shadow: true,
			iconCls:"addicon",
			//不可以随意改变大小
			resizable:false,
			//是否可以拖动
			//draggable:false,
			defaultType:"textfield",
			labelWidth:100,
			collapsible:true, //允许缩放条
            closeAction : 'hide',
            closable:true,
            plain : true,
            //弹出模态窗体
			modal: 'true', 
			buttonAlign:"center",
			bodyStyle:"padding:10px 0 0 15px",
			/*
			listeners:{
			    "show":function() {
			        //当window show事件发生时清空一下表单
			        //this.fp.getForm().loadRecord(row);
			    }
			},*/

            items: [this.fp],
            buttons: [{
                text: "保存",
                handler: this.onSave,
                scope: this
            }, {
                text: "清空",
                handler: this.reset,
                scope: this
            }, {
                text: "关闭",
                handler: this.closeWin,
                scope: this
            }]
        });
        return win;
    },
    
    //显示（新增/修改）窗口
    showWin: function(status){ //createForm()需要在继承时提供，该方法作用是创建表单
        if (!this.win) {
            if (!this.fp) {
                this.fp = this.createForm();
            }
            this.win = this.createWin(status);
            this.win.on("close", function(){
                this.win = null;
                this.fp = null;
                this.store.reload();
            }, this);
        }
        //窗口关闭时，数据重新加载
        this.win.show();
    },
    //创建（新增/修改）窗口
    create: function(){
        this.showWin("Save");
        this.reset();
    },
    
    //数据保存[（新增/修改）窗口]
    onSave: function(){
        var id = this.fp.form.findField("Id").getValue();
        this.fp.form.submit({
            waitMsg: '正在保存。。。',
            url: this.saveUrl,
            method: 'POST',
            success: function(){
                this.closeWin();
                this.store.reload();
            },
            failure:function(form,action) {
                Ext.MessageBox.alert("提示!","信息操作失败!");
            },
            scope: this
        });
    },
    //（新增/修改）窗口上的清空
    reset: function(){
        if (this.win) 
            this.fp.form.reset();
    },
    //（新增/修改）窗口上的关闭
    closeWin: function(){
        if (this.win) 
            this.win.close();
        this.win = null;
        this.fp = null;
        this.store.reload();
    },
    //修改，双击行，或选中一行点击修改，
    onEdit: function(){
        if (this.gridPanel.selModel.hasSelection()) {
            var records = this.gridPanel.selModel.getSelections();//得到被选择的行的数组
            var recordsLen = records.length;//得到行数组的长度
            if (recordsLen > 1) {
                Ext.Msg.alert("系统提示信息", "请选择其中一项进行编辑！");
            }//一次只给编辑一行
            else {
                var record = this.gridPanel.getSelectionModel().getSelected();//获取选择的记录集
                //var id = record.get("id");
                this.showWin("Update");
                this.fp.form.loadRecord(record); //往表单（fp.form）加载数据
            }
        }
        else {
            Ext.Msg.alert("提示", "请先选择要编辑的行!");
        }
    },
	/**
	 * 取消修改一条数据
	 */
	cancelOneData:function (){
	    var grid  = this.gridPanel;
	    var store = this.store;
		var rid=grid.selModel.selections.keys; 
 	 	if(rid ==''||rid==null){
 	 		Ext.Msg.show({title: '没有选择项',msg: '请至少选择一项',modal: true,
                	 icon: Ext.Msg.INFO,buttons: Ext.Msg.OK}); return ;}
 	 	var recordInfo = store.getById(rid);
			recordInfo.reject();
 	    Ext.example.msg('信息', '已经撤销修改！');
		},
	/**
	 * 查看记录
	 */
	viewOneData:function  (){
  	 var rid=this.gridPanel.selModel.selections.keys; 
  	 if(rid ==''||rid==null){
 	 			Ext.Msg.show({title: '没有选择项',msg: '请至少选择一项',modal: true,
                	 icon: Ext.Msg.INFO,buttons: Ext.Msg.OK}); return ;}
   		var recordInfo =  this.store.getById(rid);
   		//var dataId= recordInfo.get("id");
   		this.showWin();
	    this.fp.form.loadRecord(record); 
	},
	/**
	 * 增加一条默认记录
	 */ 
 	addOneData:function () {
 		var grid  = this.gridPanel;
	    var store = this.store;
  		 grid.stopEditing();
  	      // a new Record
	  	 var dataRecord = new Ext.data.Record.create(this.dataFields)(this.dataModel);
     	 store.insert(0, dataRecord);
    	 grid.startEditing(0, 2); 
 	 },
	/**
	 * 删除一条记录
	 */
	 deleteOneData:function (){
 		var store =this.store;
 		var grid  =this.gridPanel;
 		var saveUrl = this.saveUrl;
 		var rid=grid.selModel.selections.keys; 
   		if(rid ==''||rid==null){
 	 	Ext.Msg.show({title: '没有选择项',msg: '请至少选择一项',modal: true,
                	 icon: Ext.Msg.INFO,buttons: Ext.Msg.OK}); return ;}
    	Ext.Msg.confirm('删除操作', '删除将无法恢复,是否继续?', function(btn, text){
 		if (btn == 'yes'){              	 
	    var recordInfo = store.getById(rid);
	    var dataId= recordInfo.get("id");
	    if(!dataId){store.remove(recordInfo); Ext.example.msg('信息', '已经删除该记录！'); return ; }	
	   	// 数据库操作
	   	Ext.Ajax.request({
        url: saveUrl,
        params:{
         	id: dataId,
    		mode:'json',
    		method:'delete'
        },
        success: function(response, options){
        	 try {
					var responseData = Ext.decode(response.responseText);
           			if (responseData.success == true) {
              			store.remove(recordInfo);
           	    	 Ext.example.msg('信息', '数据删除成功！');  
            		 } else { Ext.example.msg('提示', '删除失败！');}
            } catch (e) { Ext.example.msg('提示', '删除失败！请稍后再尝试');}
        },
        failure: function(response, options){Ext.example.msg('警告!', '服务端发生错误,数据删除失败!');}
    }); 
  	}
		}); 			 
 	},
 	/**
	 * 保存一条数据
	 */
 	saveOneData:function (){
  	var store = this.store;
 	var grid  = this.gridPanel;
  	var rid=grid.selModel.selections.keys; 
 	 if(rid ==''||rid==null){
 	 	Ext.Msg.show({title: '没有选择项',msg: '请至少选择一项',modal:true,
                	 icon: Ext.Msg.INFO,buttons: Ext.Msg.OK}); return ;}
 	var recordInfo = store.getById(rid);
 	// 如果没有修改 直接返回
 	if(!recordInfo.modified){Ext.example.msg('信息', '数据没有变动,无须保存！');return;}
   	var fields = this.dataFields||"";
   	var urlparams = "method=save&mode=json&";
   	for(var j = 0, jlen = fields.length; j < jlen; j++){
            var f = fields[j].name;
            var v = recordInfo.get(f);
             if(!Ext.isEmpty(v)) {
               if(Ext.isDate(v)){
                v= Jinyi.project.Format.formatDateRenderer(v);
               }
               urlparams = urlparams +　f +　"=" + v;
              if(j+1 != jlen) urlparams = urlparams+ "&";
        	}
     	}
    urlparams=encodeURI(urlparams);	
    //alert(urlparams);	
    // 数据库操作
    Ext.Ajax.request({
        url: this.saveUrl,
        params:urlparams,
        method:'POST',
        success: function(response, options){
           try {
				var responseData = Ext.decode(response.responseText);
            	if (responseData.success == true) {
                Ext.example.msg('信息', '数据修改成功！');
                	store.commitChanges() ;
	                store.removeAll();
	                store.load();
            		}else { Ext.example.msg('提示', '修改失败！');}
					} catch (e) { Ext.example.msg('提示', '修改失败！请稍后再尝试');}
        },
        failure: function(response, options){Ext.example.msg('警告!', '服务端发生错误修改失败!');}
    }); 
 	},
	/**
	 * 保存多条数据
	 */
	saveMoreData:function (){
	 	var store =this.store;
	 	var grid = this.gridPanel;
	 	var modified = store.getModifiedRecords();
	  	var len = (!!modified)?modified.length:0;
	    // 如果没有修改 直接返回
	   	if(len == 0){ Ext.example.msg('信息', '数据没有变动,无须保存！');return;}
   	  var fields = this.dataFields||"";
	  var jsonData = '[';
			for(var i = 0 ,ilen = modified.length; i <　ilen; i++){  
				jsonData = jsonData+ '{';
			 for(var j = 0, jlen = fields.length; j < jlen; j++){
	            var f = fields[j].name;
	            var v = modified[i].get(f);
		             if(!Ext.isEmpty(v)) {
		               if(Ext.isDate(v)){
		                v= Jinyi.project.Format.formatDateRenderer(v);
		               }
		               jsonData = jsonData +　f +　":'" + v +"'";
		              if(j+1 != jlen) jsonData = jsonData+ ",";
		        	 }
	     		}
	     	jsonData = jsonData + '}';
	     	if(i+1 != ilen) jsonData = jsonData+ ",";
	    	}	
	    jsonData = jsonData + ']';
	   // jsonData=Ext.encode(jsonData);

	    // 数据库操作
	    Ext.Ajax.request({
       		url: this.saveUrl,
	        params: {
	        	method: 'saveMore',
	            jsonStr: jsonData
	        },
	        method:'POST',
	        jsonData: jsonData,
	        success: function(response, options){
	           try {
				var responseData = Ext.decode(response.responseText);
	            	if (responseData.success == true) {
		              store.commitChanges();
	            	  store.removeAll();
	            	  store.load();
	                Ext.example.msg('信息', '数据修改成功!');
	            		}else { Ext.example.msg('提示', '数据修改失败!'); }
							}catch(e) { Ext.example.msg('提示', '修改失败！请稍后再尝试');}
	        },
	        failure: function(response, options){Ext.example.msg('警告!', '服务端发生错误,数据修改失败!');}
	    }); 
	}
});

